console.log('Content Script: 抖音视频下载器已加载');

// 获取视频信息的主函数
function getVideoInfo() {
    console.log('Content Script: 开始获取视频信息');
    
    let videoInfo = {
        url: null,
        title: document.title || '抖音视频',
        timestamp: Date.now()
    };

    // 方法0: 优先检查抖音特有的视频元素和属性
    console.log('Content Script: 检查抖音特有的视频元素');
    
    // 首先尝试从抖音的API数据中获取视频URL
    try {
        // 检查window对象中的抖音数据
        if (window.__INITIAL_STATE__ || window.__NUXT__ || window._SSR_HYDRATED_DATA) {
            console.log('Content Script: 检查抖音全局数据对象');
            const globalData = window.__INITIAL_STATE__ || window.__NUXT__ || window._SSR_HYDRATED_DATA;
            const videoUrl = searchForVideoUrl(globalData);
            if (videoUrl && isValidVideoUrl(videoUrl)) {
                console.log('Content Script: 从全局数据找到视频URL:', videoUrl);
                videoInfo.url = cleanVideoUrl(videoUrl);
                return videoInfo;
            }
        }
        
        // 检查页面中的JSON数据
        const scripts = document.querySelectorAll('script[type="application/json"], script:not([src])');
        for (const script of scripts) {
            if (script.textContent && (script.textContent.includes('play_addr') || script.textContent.includes('videoUrl'))) {
                try {
                    const data = JSON.parse(script.textContent);
                    const videoUrl = searchForVideoUrl(data);
                    if (videoUrl && isValidVideoUrl(videoUrl)) {
                        console.log('Content Script: 从JSON脚本找到视频URL:', videoUrl);
                        videoInfo.url = cleanVideoUrl(videoUrl);
                        return videoInfo;
                    }
                } catch (e) {
                    // 忽略JSON解析错误
                }
            }
        }
        
        // 检查页面HTML中的视频URL模式
        const htmlContent = document.documentElement.outerHTML;
        const videoUrlPatterns = [
            // 抖音视频URL模式
            /https?:\/\/[^"'\s]*(?:douyinvod|byteimg|tos|tiktokcdn|muscdn|volcengineapi|toutiaoapi)\.com[^"'\s]*\/[^"'\s]*\.(?:mp4|m3u8|flv|webm)[^"'\s]*/gi,
            // 包含play_addr的URL
            /"play_addr[^"]*":\s*"([^"]+)"/gi,
            // 包含video_url的URL
            /"video_url[^"]*":\s*"([^"]+)"/gi
        ];
        
        for (const pattern of videoUrlPatterns) {
            const matches = htmlContent.match(pattern);
            if (matches) {
                for (const match of matches) {
                    let url = match;
                    // 如果是JSON格式，提取URL值
                    if (match.includes('":')) {
                        const urlMatch = match.match(/"([^"]+)"/);
                        if (urlMatch) url = urlMatch[1];
                    }
                    
                    const cleanUrl = cleanVideoUrl(url);
                    if (cleanUrl && isValidVideoUrl(cleanUrl)) {
                        console.log('Content Script: 从HTML模式匹配找到视频URL:', cleanUrl);
                        videoInfo.url = cleanUrl;
                        return videoInfo;
                    }
                }
            }
        }
    } catch (e) {
        console.log('Content Script: 全局数据检查失败:', e);
    }
    
    // 检查抖音视频播放器的特定选择器
    const douyinVideoSelectors = [
        'video[src*="blob:"]',
        'video[data-src]',
        'video[data-video-src]',
        'video.video-player',
        'video[class*="video"]',
        'xg-video-container video',
        '.video-container video',
        '[data-e2e="video-player"] video',
        // 新增更精确的抖音选择器
        'div[data-e2e="feed-item"] video',
        'div[data-e2e="video-player-container"] video',
        '.xgplayer video',
        '[class*="player"] video'
    ];
    
    for (const selector of douyinVideoSelectors) {
        const videos = document.querySelectorAll(selector);
        console.log(`Content Script: 使用选择器 ${selector} 找到视频数量:`, videos.length);
        
        videos.forEach(video => {
            console.log('Content Script: 检查video元素:', {
                src: video.src,
                currentSrc: video.currentSrc,
                dataset: video.dataset,
                className: video.className
            });
            
            // 对于blob URL，尝试从其他属性获取真实URL
            if (video.src && video.src.startsWith('blob:')) {
                // 检查data属性
                const dataAttrs = ['data-src', 'data-video-src', 'data-url', 'data-video-url'];
                for (const attr of dataAttrs) {
                    const dataUrl = video.getAttribute(attr);
                    if (dataUrl && isValidVideoUrl(dataUrl)) {
                        console.log('Content Script: 从data属性找到视频URL:', dataUrl);
                        videoInfo.url = dataUrl;
                        videoInfo.title = document.title || '抖音视频';
                        return videoInfo;
                    }
                }
                
                // 检查父元素的data属性
                let parent = video.parentElement;
                while (parent && parent !== document.body) {
                    for (const attr of dataAttrs) {
                        const dataUrl = parent.getAttribute(attr);
                        if (dataUrl && isValidVideoUrl(dataUrl)) {
                            console.log('Content Script: 从父元素data属性找到视频URL:', dataUrl);
                            videoInfo.url = dataUrl;
                            videoInfo.title = document.title || '抖音视频';
                            return videoInfo;
                        }
                    }
                    parent = parent.parentElement;
                }
                
                // 尝试从网络请求中找到对应的真实URL
                const blobId = video.src.split('/').pop();
                console.log('Content Script: 尝试查找blob URL对应的真实URL:', blobId);
                
                // 检查performance entries中的网络请求
                const entries = performance.getEntriesByType('resource');
                for (const entry of entries) {
                    if (entry.name && isValidVideoUrl(entry.name)) {
                        console.log('Content Script: 从网络请求找到可能的视频URL:', entry.name);
                        videoInfo.url = entry.name;
                        videoInfo.title = document.title || '抖音视频';
                        return videoInfo;
                    }
                }
            } else if (video.src && isValidVideoUrl(video.src)) {
                console.log('Content Script: 从video元素找到视频URL:', video.src);
                videoInfo.url = video.src;
                videoInfo.title = document.title || '抖音视频';
                return videoInfo;
            } else if (video.currentSrc && isValidVideoUrl(video.currentSrc)) {
                console.log('Content Script: 从video元素currentSrc找到视频URL:', video.currentSrc);
                videoInfo.url = video.currentSrc;
                videoInfo.title = document.title || '抖音视频';
                return videoInfo;
            }
        });
    }

    // 方法1: 检查所有video标签
    console.log('Content Script: 检查所有video标签');
    const videos = document.querySelectorAll('video');
    console.log('Content Script: 找到video标签数量:', videos.length);
    
    for (const video of videos) {
        console.log('Content Script: 检查video元素:', {
            src: video.src,
            currentSrc: video.currentSrc,
            dataset: video.dataset,
            className: video.className
        });
        
        if (video.src && isValidVideoUrl(video.src)) {
             console.log('Content Script: 从video.src找到视频URL:', video.src);
             videoInfo.url = cleanVideoUrl(video.src);
             return videoInfo;
         }
         if (video.currentSrc && isValidVideoUrl(video.currentSrc)) {
             console.log('Content Script: 从video.currentSrc找到视频URL:', video.currentSrc);
             videoInfo.url = cleanVideoUrl(video.currentSrc);
             return videoInfo;
         }
    }

    // 方法2: 检查全局变量
    if (!videoInfo.url) {
        console.log('Content Script: 尝试从全局变量获取视频信息');
        try {
            const globalVars = [
                'window.__INITIAL_STATE__',
                'window.__NUXT__', 
                'window._SSR_HYDRATED_DATA',
                'window.RENDER_DATA',
                'window.__INITIAL_PROPS__'
            ];

            for (const varName of globalVars) {
                try {
                    const data = eval(varName);
                    if (data) {
                        console.log('Content Script: 检查全局变量:', varName);
                        const foundUrl = searchForVideoUrl(data);
                        if (foundUrl) {
                            console.log('Content Script: 从全局变量找到视频URL:', foundUrl);
                            videoInfo.url = foundUrl;
                            break;
                        }
                    }
                } catch (e) {
                    // 忽略错误，继续尝试下一个
                }
            }
        } catch (e) {
            console.log('Content Script: 全局变量获取失败:', e);
        }
    }

    // 方法3: 检查网络请求中的视频URL
    if (!videoInfo.url) {
        console.log('Content Script: 尝试从网络请求获取视频URL');
        
        // 检查页面链接
        const links = document.querySelectorAll('a[href]');
        for (const link of links) {
            if (isValidVideoUrl(link.href)) {
                console.log('Content Script: 从页面链接找到视频URL:', link.href);
                videoInfo.url = cleanVideoUrl(link.href);
                return videoInfo;
            }
        }
        
        // 检查页面源码中的URL
        const pageContent = document.documentElement.outerHTML;
        const urlPatterns = [
            // 标准视频文件扩展名
            /https?:\/\/[^\s"'<>]+\.(?:mp4|m3u8|flv|avi|mov|wmv|webm)/gi,
            // 抖音特有的视频URL模式
            /https?:\/\/[^\s"'<>]*(?:douyinvod|byteimg|tos|tiktokcdn|muscdn|volcengineapi|toutiaoapi)\.com[^\s"'<>]*/gi,
            // 包含video或play关键字的URL
            /https?:\/\/[^\s"'<>]*(?:video|play|stream)[^\s"'<>]*/gi,
            // 抖音特有的视频URL模式
            /https?:\/\/[^\s"'<>]*douyin\.com[^\s"'<>]*(?:play_addr|download_addr|\/obj\/)[^\s"'<>]*/gi
        ];
        
        for (const pattern of urlPatterns) {
            const matches = pageContent.match(pattern);
            if (matches) {
                for (const match of matches) {
                    const cleanUrl = cleanVideoUrl(match);
                    if (isValidVideoUrl(cleanUrl)) {
                        console.log('Content Script: 从页面源码找到视频URL:', cleanUrl);
                        videoInfo.url = cleanUrl;
                        return videoInfo;
                    }
                }
            }
        }
        
        // 检查网络请求记录
        try {
            const entries = performance.getEntriesByType('resource');
            for (const entry of entries) {
                if (entry.name && isValidVideoUrl(entry.name)) {
                    console.log('Content Script: 从网络请求记录找到视频URL:', entry.name);
                    videoInfo.url = cleanVideoUrl(entry.name);
                    return videoInfo;
                }
            }
        } catch (e) {
            console.log('Content Script: 获取网络请求记录失败:', e);
        }
    }

    // 方法4: 检查localStorage和sessionStorage
    if (!videoInfo.url) {
        console.log('Content Script: 尝试从存储获取视频信息');
        try {
            const storages = [localStorage, sessionStorage];
            for (const storage of storages) {
                for (let i = 0; i < storage.length; i++) {
                    const key = storage.key(i);
                    const value = storage.getItem(key);
                    if (value) {
                        try {
                            const data = JSON.parse(value);
                            const foundUrl = searchForVideoUrl(data);
                            if (foundUrl) {
                                console.log('Content Script: 从存储找到视频URL:', foundUrl);
                                videoInfo.url = foundUrl;
                                return videoInfo;
                            }
                        } catch (e) {
                            // 不是JSON，检查是否直接是URL
                            if (isValidVideoUrl(value)) {
                                console.log('Content Script: 从存储找到视频URL:', value);
                                videoInfo.url = cleanVideoUrl(value);
                                return videoInfo;
                            }
                        }
                    }
                }
            }
        } catch (e) {
            console.log('Content Script: 检查存储时出错:', e);
        }
    }

    // 方法4: 检查网络请求记录
    if (!videoInfo.url) {
        console.log('Content Script: 尝试从网络请求记录获取视频URL');
        try {
             const resources = performance.getEntriesByType('resource');
             for (const resource of resources) {
                 const cleanUrl = cleanVideoUrl(resource.name);
                 if (cleanUrl && isValidVideoUrl(cleanUrl)) {
                     console.log('Content Script: 从网络请求记录找到视频URL:', cleanUrl);
                     videoInfo.url = cleanUrl;
                     break;
                 }
             }
         } catch (e) {
             console.log('Content Script: 网络请求记录获取失败:', e);
         }
    }

    console.log('Content Script: 最终获取到的视频信息:', videoInfo);
    
    // 如果没有找到视频URL，返回错误信息而不是页面URL
    if (!videoInfo.url) {
        console.log('Content Script: 未找到有效的视频URL');
        videoInfo.error = '未找到视频URL，请确保在视频播放页面使用';
        videoInfo.url = null;
    } else {
        // 额外验证：确保获取到的不是页面URL
        if (videoInfo.url === window.location.href || 
            videoInfo.url.startsWith('https://www.douyin.com/') && !videoInfo.url.includes('.mp4') && !videoInfo.url.includes('.m3u8')) {
            console.log('Content Script: 检测到页面URL，重新搜索');
            videoInfo.error = '检测到的是页面URL而非视频文件，请在视频播放时使用';
            videoInfo.url = null;
        } else {
            console.log('Content Script: 验证通过，URL看起来是视频文件:', videoInfo.url);
        }
    }
    
    return videoInfo;
}

// 搜索对象中的视频URL
function searchForVideoUrl(obj, depth = 0) {
    if (depth > 10 || !obj) return null;
    
    try {
        // 检查常见的视频URL字段
        const videoFields = [
            'play_addr', 'playAddr', 'play_url', 'playUrl', 'video_url', 'videoUrl',
            'download_addr', 'downloadAddr', 'src', 'url', 'uri', 'play_addr_h264',
            'play_addr_h265', 'play_addr_bytevc1', 'url_list', 'backup_url_1'
        ];
        
        for (const field of videoFields) {
            if (obj[field]) {
                let url = obj[field];
                
                // 如果是对象，尝试获取url_list或uri
                if (typeof url === 'object') {
                    if (url.url_list && Array.isArray(url.url_list) && url.url_list.length > 0) {
                        url = url.url_list[0];
                    } else if (url.uri) {
                        url = url.uri;
                    } else if (url.url) {
                        url = url.url;
                    }
                }
                
                // 如果是数组，取第一个
                if (Array.isArray(url) && url.length > 0) {
                    url = url[0];
                }
                
                if (typeof url === 'string' && isValidVideoUrl(url)) {
                    console.log('Content Script: 在对象中找到视频URL字段:', field, url);
                    return url;
                }
            }
        }
        
        // 递归搜索子对象
        if (typeof obj === 'object') {
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    const result = searchForVideoUrl(obj[key], depth + 1);
                    if (result) return result;
                }
            }
        }
        
        // 如果是数组，搜索每个元素
        if (Array.isArray(obj)) {
            for (const item of obj) {
                const result = searchForVideoUrl(item, depth + 1);
                if (result) return result;
            }
        }
        
    } catch (e) {
        console.log('Content Script: 搜索视频URL时出错:', e);
    }
    
    return null;
}

// 清理和解码视频URL
function cleanVideoUrl(url) {
    if (!url || typeof url !== 'string') return null;
    
    try {
        // 移除首尾的引号、空格和反斜杠
        let cleanUrl = url.trim().replace(/^['"`\\]+|['"`\\]+$/g, '');
        
        // 解码Unicode转义字符
        cleanUrl = cleanUrl.replace(/\\u([0-9a-fA-F]{4})/g, (match, code) => {
            return String.fromCharCode(parseInt(code, 16));
        });
        
        // 解码常见的转义字符
        cleanUrl = cleanUrl.replace(/\\u0026/g, '&')
                          .replace(/\\u003d/g, '=')
                          .replace(/\\u003f/g, '?')
                          .replace(/\\u002f/g, '/')
                          .replace(/\\u003a/g, ':')
                          .replace(/\\\\/g, '\\')
                          .replace(/\\"/g, '"')
                          .replace(/\\'/g, "'");
        
        // 尝试URL解码
        try {
            if (cleanUrl.includes('%')) {
                cleanUrl = decodeURIComponent(cleanUrl);
            }
        } catch (e) {
            // 如果解码失败，使用原URL
            console.log('Content Script: URL解码失败，使用原URL');
        }
        
        // 确保URL格式正确
        if (cleanUrl && !cleanUrl.startsWith('http')) {
            if (cleanUrl.startsWith('//')) {
                cleanUrl = 'https:' + cleanUrl;
            } else if (cleanUrl.startsWith('/')) {
                cleanUrl = 'https://www.douyin.com' + cleanUrl;
            }
        }
        
        console.log('Content Script: URL清理结果:', url, '->', cleanUrl);
        return cleanUrl;
    } catch (e) {
        console.log('Content Script: URL清理失败:', e);
        return url;
    }
}

// 验证是否为有效的视频URL
function isValidVideoUrl(url) {
    if (!url || typeof url !== 'string') return false;
    
    // 排除明显的非视频资源
    const excludePatterns = [
        /\/favicon\.ico$/i,
        /\/robots\.txt$/i,
        /\.css(\?|$)/i,
        /\.js(\?|$)/i,
        /\.json(\?|$)/i,
        /\.xml(\?|$)/i,
        /\.txt(\?|$)/i,
        /\.html(\?|$)/i,
        /\.htm(\?|$)/i,
        /\.php(\?|$)/i,
        /\.jsp(\?|$)/i,
        /\.asp(\?|$)/i,
        /x-storage-web/i,
        /\/api\//i,
        /\/ajax\//i,
        /\/static\//i,
        /\/assets\//i,
        /\/images\//i,
        /\/img\//i,
        /\/css\//i,
        /\/js\//i,
        /\/fonts\//i,
        /\.woff/i,
        /\.ttf/i,
        /\.eot/i,
        /\.svg/i,
        /\.png/i,
        /\.jpg/i,
        /\.jpeg/i,
        /\.gif/i,
        /\.webp/i,
        /\.ico/i,
        // 排除抖音页面URL（不包含视频文件扩展名的）
        /^https:\/\/www\.douyin\.com\/(?!.*\.(mp4|m3u8|flv|webm))/i
    ];
    
    // 检查排除模式
    for (const pattern of excludePatterns) {
        if (pattern.test(url)) {
            console.log('Content Script: URL被排除模式匹配:', url, pattern);
            return false;
        }
    }
    
    // 抖音视频URL模式（更严格的匹配）
    const douyinVideoPatterns = [
        // 直接的视频文件URL
        /\.(mp4|m3u8|flv|webm|avi|mov|3gp)(\?|$)/i,
        // 抖音CDN域名的视频URL
        /https?:\/\/[^\/]*(?:douyinvod|byteimg|tos|tiktokcdn|muscdn|volcengineapi|toutiaoapi)\.com.*\.(mp4|m3u8|flv|webm)/i,
        // 包含play_addr的URL（通常是视频播放地址）
        /play_addr.*\.(mp4|m3u8|flv|webm)/i,
        // 抖音特有的视频URL模式
        /\/video\/tos\/[^\/]+\/[^\/]+\//i,
        // 字节跳动CDN的视频URL
        /p\d+\.douyinpic\.com.*\.(mp4|m3u8)/i,
        // 抖音API返回的视频URL
        /aweme\/v\d+\/play/i
    ];
    
    // 检查抖音视频模式
    for (const pattern of douyinVideoPatterns) {
        if (pattern.test(url)) {
            console.log('Content Script: URL匹配抖音视频模式:', url, pattern);
            return true;
        }
    }
    
    // 通用视频URL模式（作为后备）
    const generalVideoPatterns = [
        /\.(mp4|webm|ogg|avi|mov|wmv|flv|3gp|mkv|m4v|m3u8)(\?.*)?$/i,
        /\/video\//i,
        /\/media\//i,
        /content-type.*video/i
    ];
    
    for (const pattern of generalVideoPatterns) {
        if (pattern.test(url)) {
            console.log('Content Script: URL匹配通用视频模式:', url, pattern);
            return true;
        }
    }
    
    console.log('Content Script: URL未匹配任何视频模式:', url);
    return false;
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('Content Script: 收到消息:', request);
    
    if (request.type === 'GET_VIDEO_INFO') {
        const videoInfo = getVideoInfo();
        console.log('Content Script: 返回视频信息:', videoInfo);
        sendResponse(videoInfo);
    }
    
    return true;
});

// 页面加载完成后执行
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        console.log('Content Script: DOM加载完成，开始获取视频信息');
        setTimeout(getVideoInfo, 2000);
    });
} else {
    setTimeout(() => {
        console.log('Content Script: 页面已加载，开始获取视频信息');
        getVideoInfo();
    }, 1000);
}

console.log('Content Script: 抖音视频下载器 content script 初始化完成');